<?php

    function osc_match_mos_user ( $userid = null, $reverse = 0 ) {
    global $mainframe, $database, $mosUser, $database, $my;
    

    if ( !$userid && !$mosUser['id'] && !$my->id ) {
    return; 
    }
    elseif ( !$userid && $mosUser['id'] ) { $userid = $mosUser['id']; }
    elseif ( !$userid && $my->id) {$userid = $my->id; }

    $database->setQuery( "SELECT * FROM #__users WHERE id='$userid'" );

    if ($database->loadObject( $mosUser ) ) {
      $oscQuery = tep_db_query("SELECT * FROM " . TABLE_CUSTOMERS . " WHERE customers_id='$userid'" );
      if ( tep_db_num_rows($oscQuery) ) {
        $oscUser = tep_db_fetch_array($oscQuery);

        if ( $reverse ) {
          $upUser = new mosUser( $database );
          $upUser->load( $mosUser['id'] );
        } else {
          $upUser = array();
          $fName = preg_replace('/^(.+?)\s.*$/','$1',$mosUser['name']);
          if ($fName != $mosUser['name']) {
            $lName = preg_replace('/^.+?\s(.+)$/','$1',$mosUser['name']);
            $lName = preg_replace('/^\s*(.+)\s*/','$1',$lName);
          } else { $lName = null; };
        }

        $update = 0;
        if ( $reverse ) {
          $mergName = $oscUser['customers_firstname'] . ' ' . $oscUser['customers_lastname'];
          if ( $mosUser['name'] != $mergName ) {
            $upUser->name = $mergName;
            $update = 1;
          }
          if ( $mosUser['email'] != $oscUser['customers_email_address'] ) {
            $upUser->email = $oscUser['customers_email_address'];
            $update = 1;
          }
          if ( $mosUser['password'] != $oscUser['customers_password'] ) {
            $upUser->password = $oscUser['customers_password'];
            $update = 1;
          }
        } else {
          if ( ( $fName && $lName ) &&
             ( ($fName != $oscUser['customers_firstname'])||($lName != $oscUser['customers_lastname']) ) ) {
            $upUser['customers_firstname'] = $fName;
            $upUser['customers_lastname']  = $lName;
            $update = 1;
          }
          if ($mosUser['email'] != $oscUser['customers_email_address']) {
            $upUser['customers_email_address'] = $mosUser['email'];
            $update = 1;
          }
          if ($mosUser['password'] != $oscUser['customers_password']) {
            $upUser['customers_password'] = $mosUser['password'];
            $update = 1;
          }
        }
        if ( $update ) {
          if ( $reverse ) {
            $upUser->store();
          } else {
            tep_db_perform(TABLE_CUSTOMERS, $upUser, 'update', "customers_id = '" . (int)$userid . "'");
          }
        }
      }
    }

  }; // osc_match_mos_user

  function mos_get_user( $email_address = null ) {
    global $database, $mainframe;

    // Pull Current MOS User Data
    if ( $email_address ){
		 if ($customer_id != 0) {
      $customer_query = tep_db_query("select customers_id FROM " . TABLE_CUSTOMERS . " WHERE customers_email_address='$email_address'" );
      }
      if (tep_db_num_rows($customer_query)) {
        $customer = tep_db_fetch_array($customer_query);
        $database->setQuery( "SELECT * FROM #__users WHERE id='".$customer['customers_id']."'" );
      } else {
        $database->setQuery( "SELECT * FROM #__users WHERE email='$email_address'" );
      }
      if ($row = $database->loadObject( $row )) {
        return $row;
      };
      
    }

    return null;
  }; // mos_get_username

  //function mos_load_credentials( ) {
  //renamed
  function ecjc_load_credentials( ) {
    global $mosUser, $customer_id, $customer_default_address_id, $customer_first_name, $my;
    global $customer_country_id, $customer_zone_id, $database, $mainframe, $cart, $navigation, $origin_href, $wishlist, $sppc_customer_group_id, $sppc_customer_group_show_tax, $sppc_customer_group_tax_exempt;

    // Pull Current MOS User Data
    foreach ( $my as $key => $val ) { $mosUser[$key] = $val; };

    // Load the User MOS credentials into the $mosUser hash
    if ( $my->username && $my->id ) {
        $database->setQuery( "SELECT * FROM #__users"
        . "\n WHERE username='".$my->username."' AND block='0'"
        );

        $row = null;
        if ($row = $database->loadObject($row)) {
       
            foreach ( $row as $key => $val ) { $mosUser[$key] = $val; };
            $mosUser['validated'] = 1;


            $check_customer_query = tep_db_query("select customers_id, customers_firstname, customers_group_id, customers_password, customers_email_address, customers_default_address_id from " . TABLE_CUSTOMERS . " where customers_id = '" . tep_db_input($my->id) . "'");
            if (!tep_db_num_rows($check_customer_query)) {
              // User Not Valid
              // osc_create_user_account( $mosUser );
            } else {
              $check_customer = tep_db_fetch_array($check_customer_query);
              if (SESSION_RECREATE == 'True') {
                tep_session_recreate();
              }

if ($_GET['skip'] != 'true' && $_POST['email_address'] == SPPC_TOGGLE_LOGIN_PASSWORD ) {
   $existing_customers_query = tep_db_query("select customers_group_id, customers_group_name from " . TABLE_CUSTOMERS_GROUPS . " order by customers_group_id ");
echo '<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">';
print ("\n<html ");
echo HTML_PARAMS;
print (">\n<head>\n<title>Choose a Customer Group</title>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=");
echo CHARSET;
print ("\"\n<base href=\"");
echo (($request_type == 'SSL') ? HTTPS_SERVER : HTTP_SERVER) . DIR_WS_CATALOG;
print ("\">\n<link rel=\"stylesheet\" type=\"text/css\" href=\"stylesheet.css\">\n");
echo '<body bgcolor="#ffffff" style="margin:0">';
print ("\n<table border=\"0\" width=\"100%\" height=\"100%\">\n<tr>\n<td style=\"vertical-align: middle\" align=\"middle\">\n");
echo tep_draw_form('login', tep_href_link(FILENAME_LOGIN, 'action=process&skip=true', 'SSL'));
print ("\n<table border=\"0\" bgcolor=\"#f1f9fe\" cellspacing=\"10\" style=\"border: 1px solid #7b9ebd;\">\n<tr>\n<td class=\"main\">\n");
  $index = 0;
  while ($existing_customers =  tep_db_fetch_array($existing_customers_query)) {
 $existing_customers_array[] = array("id" => $existing_customers['customers_group_id'], "text" => "&#160;".$existing_customers['customers_group_name']."&#160;");
    ++$index;
  }
print ("<h1>Choose a Customer Group</h1>\n</td>\n</tr>\n<tr>\n<td align=\"center\">\n");
echo tep_draw_pull_down_menu('new_customers_group_id', $existing_customers_array, $check_customer['customers_group_id']);
print ("\n<tr>\n<td class=\"main\">&#160;<br />\n&#160;");
print ("<input type=\"hidden\" name=\"email_address\" value=\"".$_POST['email_address']."\">");
print ("<input type=\"hidden\" name=\"password\" value=\"".$_POST['password']."\">\n</td>\n</tr>\n<tr>\n<td align=\"right\">\n");
echo tep_image_submit('button_continue.gif', IMAGE_BUTTON_CONTINUE);
print ("</td>\n</tr>\n</table>\n</form>\n</td>\n</tr>\n</table>\n</body>\n</html>\n");
exit;
}
// EOF Separate Pricing Per Customer: choice for logging in under any customer_group_id

              $check_country_query = tep_db_query("select entry_country_id, entry_zone_id from " . TABLE_ADDRESS_BOOK . " where customers_id = '" . (int)$check_customer['customers_id'] . "' and address_book_id = '" . (int)$check_customer['customers_default_address_id'] . "'");
              $check_country = tep_db_fetch_array($check_country_query);

              $customer_id = $check_customer['customers_id'];
              $customer_default_address_id = $check_customer['customers_default_address_id'];
              $customer_first_name = $check_customer['customers_firstname'];
              // BOF Separate Pricing per Customer
	if ($_GET['skip'] == 'true' && $_POST['email_address'] == SPPC_TOGGLE_LOGIN_PASSWORD && isset($_POST['new_customers_group_id']))  {
	$sppc_customer_group_id = $_POST['new_customers_group_id'] ;
	$check_customer_group_tax = tep_db_query("select customers_group_show_tax, customers_group_tax_exempt from " . TABLE_CUSTOMERS_GROUPS . " where customers_group_id = '" .(int)$_POST['new_customers_group_id'] . "'");
	} else {
	$sppc_customer_group_id = $check_customer['customers_group_id'];
	$check_customer_group_tax = tep_db_query("select customers_group_show_tax, customers_group_tax_exempt from " . TABLE_CUSTOMERS_GROUPS . " where customers_group_id = '" .(int)$check_customer['customers_group_id'] . "'");
	}
	$customer_group_tax = tep_db_fetch_array($check_customer_group_tax);
	$sppc_customer_group_show_tax = (int)$customer_group_tax['customers_group_show_tax'];
	$sppc_customer_group_tax_exempt = (int)$customer_group_tax['customers_group_tax_exempt'];
	// EOF Separate Pricing per Customer
              $customer_country_id = $check_country['entry_country_id'];
              $customer_zone_id = $check_country['entry_zone_id'];
              tep_session_register('customer_id');
              tep_session_register('customer_default_address_id');
              tep_session_register('customer_first_name');
              tep_session_register('customer_country_id');
              tep_session_register('customer_zone_id');
              // BOF Separate Pricing per Customer
	tep_session_register('sppc_customer_group_id');
	tep_session_register('sppc_customer_group_show_tax');
	tep_session_register('sppc_customer_group_tax_exempt');
	// EOF Separate Pricing per Customer

              tep_db_query("update " . TABLE_CUSTOMERS_INFO . " set customers_info_date_of_last_logon = now(), customers_info_number_of_logons = customers_info_number_of_logons+1 where customers_info_id = '" . (int)$customer_id . "'");

              // restore cart contents
              $cart->restore_contents();
              // restore wishlist to sesssion V1.1.7


// Create the WISHLIST
  if (!is_object($wishlist)) {

    tep_session_register('wishlist');
    $wishlist = new wishlist_class;
  }
              $wishlist->restore_contents();

              if (sizeof($navigation->snapshot) > 0) {
                $origin_href = tep_href_link($navigation->snapshot['page'], tep_array_to_string($navigation->snapshot['get'], array(tep_session_name())), $navigation->snapshot['mode']);
                $navigation->clear_snapshot();
              }

              osc_match_mos_user( $my->id );
            }
        };
    };
  }; // mos_load_credentials

  function mos_create_user_account( ) {
    global $database, $my, $acl, $mosUser, $mainframe;
    global $mosConfig_sitename, $mosConfig_live_site, $mosConfig_useractivation, $mosConfig_allowUserRegistration;
    global $mosConfig_mailfrom, $mosConfig_fromname, $mosConfig_mailfrom, $mosConfig_fromname;

    if ($mosConfig_allowUserRegistration=="0") {
      mosNotAuth();
      return _NOT_AUTH;
    }
    
    

    $row = new mosUser( $database );

    if (!$row->bind( $_POST, "usertype" )) {
      return $row->getError();
    }

    mosMakeHtmlSafe($row);

    $row->id = 0;
    $row->usertype = '';
    $row->gid = $acl->get_group_id('Registered','ARO');

    if ($mosConfig_useractivation=="1") {
      $row->activation = md5( mosMakePassword() );
      $row->block = "1";
    }

    if (!$row->check()) {
      return $row->getError();
    }

    $pwd = $row->password;
    $row->password = md5( $row->password );
    $row->registerDate = date("Y-m-d H:i:s");

    if (!$row->store()) {
      return $row->getError();
    }
    $row->checkin();

    $name = $row->name;
    $email = $row->email;
    $username = $row->username;

if(defined('_USEND_MSG')){
    $subject = sprintf (_SEND_SUB, $name, $mosConfig_sitename);
    $subject = html_entity_decode($subject, ENT_QUOTES);
    if ($mosConfig_useractivation=="1"){
      $message = sprintf (_USEND_MSG_ACTIVATE, $name, $mosConfig_sitename, $mosConfig_live_site."/index.php?option=com_registration&task=activate&activation=".$row->activation, $mosConfig_live_site, $username, $pwd);
    } else {
      $message = sprintf (_USEND_MSG, $name, $mosConfig_sitename, $mosConfig_live_site);
    }
    }

    // Load MOS User Credentials
    $database->setQuery( "SELECT * FROM #__users"
    . "\nWHERE username='".$row->username."' AND name='".$row->name."' AND email='".$row->email."'"
    );
    $row = null;
    if ($row = $database->loadObject( $row )) {
      foreach ( $row as $key => $val ) { $mosUser[$key] = $val; };
      if (!$mosUser['blocked'] && !$mosUser['activation']) {
        $mosUser['validated'] = 1;
      };
    }

    $message = html_entity_decode($message, ENT_QUOTES);
    // Send email to user
    if ($mosConfig_mailfrom != "" && $mosConfig_fromname != "") {
      $adminName2 = $mosConfig_fromname;
      $adminEmail2 = $mosConfig_mailfrom;
    } else {
      $database->setQuery( "SELECT name, email FROM #__users"
      ."\n WHERE usertype='superadministrator'" );
      $rows = $database->loadObjectList();
      $row2 = $rows[0];
      $adminName2 = $row2->name;
      $adminEmail2 = $row2->email;
    }

    mosMail($adminEmail2, $adminName2, $email, $subject, $message);

    // Send notification to all administrators
    $subject2 = sprintf (_SEND_SUB, $name, $mosConfig_sitename);
    $message2 = sprintf (_ASEND_MSG, $adminName2, $mosConfig_sitename, $row->name, $email, $username);
    $subject2 = html_entity_decode($subject2, ENT_QUOTES);
    $message2 = html_entity_decode($message2, ENT_QUOTES);

    // get superadministrators id
    $admins = $acl->get_group_objects( 25, 'ARO' );

    foreach ( $admins['users'] AS $id ) {
      $database->setQuery( "SELECT email, sendEmail FROM #__users"
        ."\n WHERE id='$id'" );
      $rows = $database->loadObjectList();

      $row = $rows[0];

      if ($row->sendEmail) {
        mosMail($adminEmail2, $adminName2, $row->email, $subject2, $message2);
      }
    }

    return $mosConfig_useractivation;
  }; // mos_create_user_account

  function osc_create_user_account ( $importUser ) {
    global $messageStack;
    if ( !$importUser ) { global $mosUser; } else { $mosUser = $importStack; }
  }; // osc_create_user_account


//j1.5

  function j15_create_user_account( ) {
       global $database, $my, $acl, $mosUser, $mainframe;
    global $mosConfig_sitename, $mosConfig_live_site, $mosConfig_useractivation, $mosConfig_allowUserRegistration;
    global $mosConfig_mailfrom, $mosConfig_fromname, $mosConfig_mailfrom, $mosConfig_fromname;


    

    $row = new mosUser( $database );

    if (!$row->bind( $_POST, "usertype" )) {
      return $row->getError();
    }

    mosMakeHtmlSafe($row);

    $row->id = 0;
    $row->usertype = '';
    $row->gid = $acl->get_group_id('Registered','ARO');

    if ($mosConfig_useractivation=="1") {
      $row->activation = md5( mosMakePassword() );
      $row->block = "1";
    }

    if (!$row->check()) {
      return $row->getError();
    }

    $pwd = $row->password;
    $row->password = md5( $row->password );
    $row->registerDate = date("Y-m-d H:i:s");

    if (!$row->store()) {
      return $row->getError();
    }
    $row->checkin();

    $name = $row->name;
    $email = $row->email;
    $username = $row->username;


    $subject = sprintf (ACCOUNT_DETAILS_FOR, $name, $mosConfig_sitename);
    $subject = html_entity_decode($subject, ENT_QUOTES);
    if ($mosConfig_useractivation=="1"){
      $message = sprintf (SEND_MSG_ACTIVATE, $name, $mosConfig_sitename, $mosConfig_live_site."/index.php?option=com_user&task=activate&activation=".$row->activation, $mosConfig_live_site, $username, $pwd);
    } else {
      $message = sprintf (SEND_MSG, $name, $mosConfig_sitename, $mosConfig_live_site);
    }
    

    // Load MOS User Credentials
    $database->setQuery( "SELECT * FROM #__users"
    . "\nWHERE username='".$row->username."' AND name='".$row->name."' AND email='".$row->email."'"
    );
    $row = null;
    if ($row = $database->loadObject($row)) {
      foreach ( $row as $key => $val ) { $mosUser[$key] = $val; };
      if (!$mosUser['blocked'] && !$mosUser['activation']) {
        $mosUser['validated'] = 1;
      };
    }

    $message = html_entity_decode($message, ENT_QUOTES);
    // Send email to user
    if ($mosConfig_mailfrom != "" && $mosConfig_fromname != "") {
      $adminName2 = $mosConfig_fromname;
      $adminEmail2 = $mosConfig_mailfrom;
    } else {
      $database->setQuery( "SELECT name, email FROM #__users"
      ."\n WHERE usertype='superadministrator'" );
      $rows = $database->loadObjectList();
      $row2 = $rows[0];
      $adminName2 = $row2->name;
      $adminEmail2 = $row2->email;
    }

    mosMail($adminEmail2, $adminName2, $email, $subject, $message);

    // Send notification to all administrators
    $subject2 = sprintf (ACCOUNT_DETAILS_FOR, $name, $mosConfig_sitename);
    $message2 = sprintf (SEND_MSG_ADMIN, $adminName2, $mosConfig_sitename, $row->name, $email, $username);
    $subject2 = html_entity_decode($subject2, ENT_QUOTES);
    $message2 = html_entity_decode($message2, ENT_QUOTES);

    // get superadministrators id
    $admins = $acl->get_group_objects( 25, 'ARO' );

    foreach ( $admins['users'] AS $id ) {
      $database->setQuery( "SELECT email, sendEmail FROM #__users"
        ."\n WHERE id='$id'" );
      $rows = $database->loadObjectList();

      $row = $rows[0];

      if ($row->sendEmail) {
        mosMail($adminEmail2, $adminName2, $row->email, $subject2, $message2);
      }
    }

    return $mosConfig_useractivation;
  
  }; // j15_create_user_account
?>
